<?php

/**
 * Property Controller
 * @author	R.A.Thilini D.R <thilinipooranee@gmail.com>
 * @date	22/02/2013
 */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Property extends MY_Controller {

    public function __construct() {
        parent::__construct();

        $this->load->model('listing_model', 'listing');
        $this->load->model('user_model', 'user');
        $this->load->model('au_suburb_geo_model', 'suburb');
    }

    public function index() {
        $this->profile();
    }

    public function emailagent() {
        $config = get_config();
        $this->data['name'] = $this->input->post('emailagent_name');
        $this->data['email'] = $this->input->post('emailagent_email');
        $this->data['mobile'] = $this->input->post('emailagent_mobile');
        $emailagent_emailID = $this->input->post('emailagent_emailID');
        $this->data['message'] = $this->input->post('emailagent_message');
        $emailagent_manageremail = $this->input->post('emailagent_manageremail');


        $this->load->library('email');
        $this->email->print_debugger();
        $this->email->from($this->data['email'], $this->data['name']);
        $this->email->to($emailagent_manageremail);
        if ($emailagent_emailID != '')
            $this->email->cc($emailagent_emailID);
        $this->email->subject('Email to agent');
        $body = $this->load->view('email/_email_to_agent', $this->data, TRUE);


        $this->email->message($body);
        $this->email->set_newline("\r\n");
        $email_rc = $this->email->send();
        if ($email_rc == 0) {
            //testing email
            // echo $this->email->print_debugger();
            // die();
        }
        echo $email_rc;
    }

    public function eqnuire() {
        $eqnuirenow_id = $this->input->post('eqnuirenow_id');
        $data['name'] = $this->input->post('eqnuirenow_name');
        $data['email'] = $this->input->post('eqnuirenow_email');
        $data['phone'] = $this->input->post('eqnuirenow_mobile');
        $data['message'] = $this->input->post('eqnuirenow_message');
        $eqnuirenow_manageremail = $this->input->post('eqnuirenow_manageremail');
        $eqnuirenow_type = $this->input->post('eqnuirenow_type');



        if ($eqnuirenow_id > 0) {
            $data['property_id'] = $eqnuirenow_id;
            $data['status'] = 1;
            $this->listing->enquiry_insert($data);

            $data['link'] = site_url('property/profile/' . $eqnuirenow_type . "/" . $eqnuirenow_id);
            $this->load->library('email');
            $this->email->print_debugger();
            $this->email->from($data['email'], $data['name']);
            $this->email->to($eqnuirenow_manageremail);
            $this->email->subject('Eqnuiry');
            $body = $this->load->view('email/_eqnuiry', $data, TRUE);


            $this->email->message($body);
            $this->email->set_newline("\r\n");
            $email_rc = $this->email->send();

            echo 1;
        } else {
            echo 0;
        }
    }

    public function emailtoFriend() {
        $config = get_config();
        $this->data['name'] = $this->input->post('emailfriend_name');
        $this->data['email'] = $this->input->post('emailfriend_email');
        $emailfriend_friendemail = $this->input->post('emailfriend_friendemail');
        $proprtyemail_type = $this->input->post('proprtyemail_type');
        $this->data['message'] = $this->input->post('emailfriend_message');
        $proprtyemail_id = $this->input->post('proprtyemail_id');
        $this->data['link'] = site_url('property/profile/' . $proprtyemail_type . "/" . $proprtyemail_id);
        $this->load->library('email');
        $this->email->print_debugger();
        $this->email->from($this->data['email'], $this->data['name']);
        $this->email->to($emailfriend_friendemail);
        $this->email->subject('Check this url');
        $body = $this->load->view('email/_email_to_friend', $this->data, TRUE);


        $this->email->message($body);
        $this->email->set_newline("\r\n");
        $email_rc = $this->email->send();
        if ($email_rc == 0) {
            //testing email
            // echo $this->email->print_debugger();
            // die();
        }
        echo $email_rc;
    }

    public function profile($status, $id = 0) {
        $data = array();
        $data['notEditable'] = false;
        $data['type'] = $status;
        $data['listingStatus'] = $this->site->getArray('selling', '');
        $data['listingAddressStreetType'] = $this->site->getArray('addressStreetType');
        $data['propertySizeFeatureType'] = $this->site->getArray('propertySizeFeatureType', '');
        $data['propertyType'] = $this->site->getArray('propertyType', ' ');
        $data['exteriorType'] = $this->site->getArray('exteriorType', '');
        $data['roofingType'] = $this->site->getArray('roofingType', '');
        $data['vendors'] = $this->listing->getVendeors();

        if ($id > 0) {
            $data['listing'] = $this->listing->getOne($id);

            if (isset($data['listing']->activity_type)) {
                $data['listingStatus'] = $this->site->getArray($data['listing']->activity_type);
            }
            if (isset($data['listing']->id)) {
                $this->navigation->loadPropertyView($data, $status);
            } else {
                $this->navigation->loadPropertyError();
            }
        } else {
            $this->navigation->loadPropertyError();
        }
    }

    public function show($page = 0) {
        $this->load($page, 'show');
    }

    public function gallery($page = 0) {
        $this->load($page, 'gallery');
    }

    public function load($page = 0, $views = 'show') {
        $this->load->model('listing_model', 'listing');
        $userid = $this->session->userdata('id');
        $complete = 0;
        $search = '';
        $status = $this->uri->segment(3);

        $this->load->library("pagination");
        $config = array();

        $searchVals = $this->input->post('searchby');
        $searchSurrounding = 0;
        $searchsuberubID = '';
        $searchsuberub = '';
        if ($searchVals != '' && is_array($searchVals)) {
            $searchArray = array('search_maxprice',
                'search_minprice',
                'search_bathroom',
                'search_bedroom',
                'search_propertytype',
                'suburbs_id',
                'suburbs',
                'surrounding',
                'search_status');
            foreach ($searchVals as $searchVal) {
                $name = $searchVal['name'];
                $value = trim($searchVal['value']);
                if (in_array($name, $searchArray) && $value != '' && $value != null) {
                    $search[$name] = $searchVal['value'];
                } else if ($name == 'view' && $value != '' && $value != null) {
                    $views = $value;
                }
                if ($name == 'surrounding' && $value != '') {
                    $searchSurrounding = 1;
                }
                if ($name == 'suburbs_id' && $value != '') {
                    $searchsuberubID = $value;
                }
                if ($name == 'suburbs' && $value != '') {
                    $searchsuberub = $value;
                }
            }
        }

        $arroundWhere = array();

        if ($searchsuberubID != '' && $searchSurrounding == 1) {
            $arroundWhere = $this->listing->around_suburbs($searchsuberubID);
        } else if ($searchsuberubID != '') {
            $search['suburbsSearch'] = $searchsuberub;
        }

        $sortby = trim($this->input->post('sortby'));
        $type = $this->input->post('contoller');
        if ($type != '')
            $status = $type;

        $contoller = 'buying/listings';

        if ($status == 'listings') {
            $contoller = 'buying/listings';
        }
        if ($status == 'rentals') {
            $contoller = 'tenant/rentals';
        }if ($status == 'sold') {
            $contoller = 'selling/sold';
        }if ($status == 'leased') {
            $contoller = 'tenant/leased';
        }

        $order = trim($this->input->post('order'));
        if ($order != 'asc' && $order != 'desc')
            $order = 'desc';


        if ($search == '' || !is_array($search)) {
            $search = array();
        }

        if (count($search) > 0) {
            $config["base_url"] = base_url() . "index.php/" . $contoller . "/" . $views . "/" . $sortby . "/" . $order . "/" . urlencode(serialize($search));
        } else {
            $config["base_url"] = base_url() . "index.php/" . $contoller . "/" . $views . "/" . $sortby . "/" . $order;
        }

        $config["uri_segment"] = 4;
        $config["total_rows"] = $this->listing->count_listing($status, $search, $arroundWhere);


        if ($views == 'gallery')
            $config["per_page"] = 8;
        else
            $config["per_page"] = 4;



        $this->pagination->initialize($config);

        $page = trim($this->input->post('page'));

        $returnData['search'] = $search;
        $returnData['sortby'] = $sortby;
        $returnData['order'] = $order;

        if ($sortby != 'status' && $sortby != 'date' && $sortby != 'price' && $sortby != 'location') {
            $sortby = 'created_date';
        } else if ($sortby == 'date') {
            $sortby = 'created_date';
        } else if ($sortby == 'status') {
            $sortby = 'status';
        } else if ($sortby == 'price') {
            $sortby = 'price_min ' . $order . ', price_max';
        } else if ($sortby == 'location') {
            $sortby = 'location';
        }


        $propertes = $this->listing->getCurrent($status, $search, $arroundWhere, $config["per_page"], $page, $sortby, $order);
        $returnData["links"] = $this->pagination->create_links();
        $returnData["total"] = $config["total_rows"];
        $page = ($page == 0) ? $page = 1 : $page;

        if (count($propertes) > 0)
            $returnData["links"].='<div class="nav-pageinfo" style="">Page ' . ceil(($page + 1) / $config["per_page"]) . ' of ' . ceil($config["total_rows"] / $config["per_page"]) . '</div>';

        $this->load->library('Mobiledetect');
        $this->load->library('session');
        if ($views == 'gallery')
            $returnData['tasks'] = $this->getGallery($propertes);
        else {
            $mobile = $this->session->userdata('mobile');
            if ($this->mobiledetect->isMobile() && $mobile != 'off') {
                $returnData['tasks'] = $this->getTableMobile($propertes);
            } else {
                $returnData['tasks'] = $this->getTable($propertes);
            }
        }



        echo json_encode($returnData);
    }

    protected function getGallery($data = array()) {


        $html = '<div class="properties-gallery-page">';

        $i = 1;
        foreach ($data as $proporty) {

            $id = $proporty->id;
            $class1 = '';
            if ($i == 1)
                $class1 = 'first ';

            $class = 'odd';
            if ($i % 2 == 0)
                $class = 'even';


            $html.='<div class="property clearfix">';

            $image = base_url() . 'img/noimage.png';
            $mainImage = $this->listing->getImage($id);
            if ($mainImage != false) {
                $image = $mainImage->image_url;
            }
            $html.='<div class="property-image" onclick="openProperty(' . $id . ')" >';
            $html.='<a href="#" onclick="openProperty(' . $id . ')" class="post-image">';
            $html.='<div>';
            $html.='<img class="photo" src="' . $image . '" alt=""/>';
            $html.='</div>';
            $html.='</a> ';
            $html.='<a href="">';
            $html.='<img src="' . base_url() . 'img/image2.png" alt="" title="View on Map" align="right" style="margin: 6px 12px 0px 0px;" />';
            $html.='</a>';
            $html.='</div>';
            $html.='<div class="property-details">';
            $html.='<h2>';
            $html.='<a title="' . $proporty->headline . '" onclick="openProperty(' . $id . ')"  href="#">';
            $html.=$proporty->headline;
            $html.='</a>';
            $html.='</h2>';
            $address = '';
            $address .= ucwords($proporty->address_street_no . ' ' . $proporty->address_street . ' ' . $proporty->address_street_type . ' ' . $proporty->address_suburb . ' ' . $proporty->address_postcode . ' ' . $proporty->address_state);
            $html.=$address;
            $html.='</div>';
            $html.='<div class="property-meta">';
            $html.='<div class="price clearfix">';
            $price = $proporty->display_price;
            if ($price == '' && $proporty->price_min != $proporty->price_max)
                $price = '$' . $proporty->price_min . ' - $' . $proporty->price_max;
            else if ($price == '' && $proporty->price_min == $proporty->price_max)
                $price = '$' . $proporty->price_min;
            $html.=$price;
            $html.='</div>';
            $html.='<div class="rooms">';
            $html.='<span class="picon beds">' . $proporty->bedrooms . '</span> <span class="picon baths">' . $proporty->bathrooms . '</span>';
            $html.='<span class="picon cars">' . $proporty->carparks . '</span> <span class="picon landarea">' . $proporty->land_size . ' ' . $proporty->land_size_type . '</span>';
            $html.='</div>';
            $html.='</div>';
            $html.='</div>';


            $i++;
        }
        $html .='</div>';
        return $html;
    }
    
    protected function getTable($data = array()) {


        $html = ' <ol class="properties list-view">';
        $i = 1;
        foreach ($data as $proporty) {

            $id = $proporty->id;
            $class1 = '';
            if ($i == 1)
                $class1 = 'first ';

            $class = 'odd';
            if ($i % 2 == 0)
                $class = 'even';

            $html.=' <li class="' . $class1 . $class . '" id="listing-' . $id . '">';


            $html.='<div class="property clearfix" >';
            $image = base_url() . 'img/noimage.png';
            $mainImage = $this->listing->getImage($id);
            if ($mainImage != false) {
                $image = $mainImage->image_url;
            }

            $html.='<div class="property-image">';
            $html.='<a href="#" onclick="openProperty(' . $id . ')" class="post-image">';
            $html.='<div>';
            $html.=' <img class="property-image" src="' . $image . '" alt="" style="padding-top: 6px;" />';
            $html.=' </div>';
            $html.=' </a> ';
            $html.='<a href="">';
            $html.='<img src="' . base_url() . 'img/image2.png" alt="" title="View on Map" align="right" style="margin: 6px 12px 0px 0px;" />';
            $html.='</a>';
            $html.='</div>';

            $html.='<div class="property-body">';

            $html.=' <h2>';
            $html.='<a title="' . $proporty->headline . '" href="#" onclick="openProperty(' . $id . ')" >';
            $html.=$proporty->headline;
            $html.=' </a>';
            $html.='</h2>';
            $address = '';
            $address .= ucwords($proporty->address_street_no . ' ' . $proporty->address_street . ' ' . $proporty->address_street_type . ' ' . $proporty->address_suburb . ' ' . $proporty->address_postcode . ' ' . $proporty->address_state);

            $html.=' <h3>' . $address . '</h3>';

            $html.='<div class="excerpt">';
            $html.=' <p>' . $proporty->description . '</p>';
            $html.='  </div>';

            $html.=' <div class="property-meta">';
            $html.=' <div class="price clearfix">';
            $price = $proporty->display_price;
            if ($price == '' && $proporty->price_min != $proporty->price_max)
                $price = '$' . $proporty->price_min . ' - $' . $proporty->price_max;
            else if ($price == '' && $proporty->price_min == $proporty->price_max)
                $price = '$' . $proporty->price_min;


            $html.= $price;
            $html.='  </div>';
            $html.=' <div class="rooms">';
            $html.=' <span class="picon beds">' . $proporty->bedrooms . '</span> <span class="picon baths">' . $proporty->bathrooms . '</span>';
            $html.='  <span class="picon cars">' . $proporty->carparks . '</span> <span class="picon landarea">' . $proporty->land_size . ' ' . $proporty->land_size_type . '</span>';
            $html.='  </div>';
            $html.='  </div>';
            $html.=' </div>';

            $html.='  </div>';
            $html.=' <div class="clearer"></div>';
            $html.=' </div>';



            $html .='</li>';
            $i++;
        }
        $html .= '</ol>';
        return $html;
    }
    
    protected function getTableMobile($data = array()) {


        $html = ' <ol class="properties list-view">';
        $i = 1;
        foreach ($data as $proporty) {

            $id = $proporty->id;
            $class1 = '';
            if ($i == 1)
                $class1 = 'first ';

            $class = 'odd ';
            if ($i % 2 == 0)
                $class = 'even';

            $html.=' <li class="' . $class1 . $class . '" id="listing-' . $id . '">';


            $html.='<div class="property clearfix" >';
            $image = base_url() . 'img/noimage.png';
            $mainImage = $this->listing->getImage($id);
            if ($mainImage != false) {
                $image = $mainImage->image_url;
            }
            $address = '';
            $address .= ucwords($proporty->address_street_no . ' ' . $proporty->address_street . ' ' . $proporty->address_street_type . ' ' . $proporty->address_suburb . ' ' . $proporty->address_postcode . ' ' . $proporty->address_state);
            $price = $proporty->display_price;
            if ($price == '' && $proporty->price_min != $proporty->price_max)
                $price = '$' . $proporty->price_min . ' - $' . $proporty->price_max;
            else if ($price == '' && $proporty->price_min == $proporty->price_max)
                $price = '$' . $proporty->price_min;
            
            $html.='<div class="property-image">';
            $html.='<a href="#" onclick="openProperty(' . $id . ')" class="post-image">';
            $html.='<div>';
            $html.=' <img width="183" class="property-image" src="' . $image . '" alt=""/>';
            $html.=' </div>';
            $html.=' </a> ';
            $html.='</div>';

            $html.='<div class="property-body">';
            $html.='<div class="property-meta">';
            $html.='<div class="price clearfix">';
            $html.= $price;
            $html.= '<div class="rooms clearfix">';
            $html.= '<span class="picon beds">'.$proporty->bedrooms.'</span>';
            $html.= '<span class="picon baths">'.$proporty->bathrooms.'</span>';
            $html.= '<span class="picon cars">'.$proporty->carparks.'</span>';
            $html.='  </div>';
            $html.='  </div>';
            $html.='  </div>';
            $html.='  </div>';
            
            $html.='<a title="' . $proporty->headline . '" class="title museo bold" href="#" onclick="openProperty(' . $id . ')" >';
            $html.=$proporty->headline;
            $html.=' </a>';
            
            $html .= '<span class="address">' . $address . '</span>';
            
            $html.='  </div>';

            
            $html .='</li>';
            $i++;
        }
        $html .= '</ol>';
        return $html;
    }

}

?>
